package com.lkm.app_ui.jz.util;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.MultiTransformation;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.load.resource.bitmap.FitCenter;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.king.app.updater.AppUpdater;
import com.king.app.updater.http.OkHttpManager;
import com.lkm.app_ui.MyApplication;
import com.lkm.app_ui.jz.bean.UpdateBean;
import com.lkm.app_ui.jz.listener.MyUpdateCallback;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@SuppressLint({"SimpleDateFormat", "DefaultLocale"})
public class JzUtil {
    public static  Gson   mGson         = new Gson();
    private static String mTimeFormat01 = "yyyy-MM-dd HH:mm:ss";
    private static String mTimeFormat02 = "yyMMddHHmmssSS";


    @SuppressLint("CheckResult")
    public static void setFitCenter(Context context, String url, ImageView iv) {
        RequestOptions options = new RequestOptions()
                .priority(Priority.HIGH) //优先级
                .fitCenter();
        //.transform(new MultiTransformation<>(new FitCenter()/*, GlideRoundTransform(raid)*/));
        Glide.with(context)
                .load(url)
                .transition(DrawableTransitionOptions.withCrossFade(300))
                .apply(options)
                .into(iv);
        iv.setScaleType(ImageView.ScaleType.FIT_CENTER);
    }

    @SuppressLint("CheckResult")
    public static void setCircleImg(Context context, String url, ImageView iv) {
        Glide.with(context)
                .load(url)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .transition(DrawableTransitionOptions.withCrossFade(300))
                .into(iv);
    }

    public static long ymd2s(String ymd) {
        long tempTime = 0L;
        if (ymd == null) return tempTime;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(mTimeFormat01);
        try {
            tempTime = simpleDateFormat.parse(ymd).getTime() / 1000;
        } catch (ParseException e) {
            tempTime = 0L;
        }
        return tempTime;
    }


    public static String toYmdHms(Long hs) {
        if (hs == 0) return "";
        Date   date   = new Date(hs * 1000L);
        String format = new SimpleDateFormat(mTimeFormat01).format(date);
        return format;
    }

    public static String createNewOrderSn(String deviceSn) {
        String time   = new SimpleDateFormat(mTimeFormat02).format(new Date());
        String random = String.format("%04d", new Random().nextInt(9999));
        Print.d("createNewOrderSn->time" + time);
        Print.d("createNewOrderSn->random" + random);
        Print.d("createNewOrderSn->deviceSn" + deviceSn);
        return deviceSn + time + random;
    }

    public static void checkUpdateApp(boolean isFirstStart) {
        Context context = MyApplication.getInstance();
        OkGo.<String>get(Urls.apkCheckUpdateUrl)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        UpdateBean updateBean = null;
                        try {
                            updateBean = JzUtil.mGson.fromJson(response.body(), UpdateBean.class);
                        } catch (Exception exception) {
                            updateBean = null;
                        }
                        if (updateBean != null) {
                            Print.d("检查更新->isFirstStart:" + isFirstStart + ",isRebootCheck:" + updateBean.isRebootCheck);
                            if (isFirstStart && !updateBean.isRebootCheck) return;
                            UpdateBean data = updateBean.data;
                            if (data != null && data.url != null && !TextUtils.isEmpty(data.url)) {
                                if (getAppVersionCode() < data.versionCode) {
                                    //TODO:更新
                                    new AppUpdater.Builder()
                                            .setChannelId(context.getPackageName())
                                            .setUrl(data.url)
                                            .setFilename("zz_scale_v" + data.versionCode + ".apk")
                                            .setInstallApk(false)
                                            .setVersionCode(data.versionCode)
                                            .build(context)
                                            .setHttpManager(OkHttpManager.getInstance())
                                            .setUpdateCallback(new MyUpdateCallback())
                                            .start();

                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        Print.showToast("更新失败："+response.getException());
                        super.onError(response);
                    }
                });
    }

    public static int getAppVersionCode() {
        int     verCode     = -1;
        Context context     = MyApplication.getInstance();
        String  packageName = context.getPackageName();
        if (TextUtils.isEmpty(packageName)) return verCode;
        PackageManager packageManager = context.getPackageManager();
        try {
            verCode = packageManager.getPackageInfo(packageName, 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            verCode = -1;
        }
        return verCode;
    }

}
